package com.wq.filter;


import com.alibaba.fastjson.JSON;
import com.wq.common.BaseContext;
import com.wq.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录检查过滤器
 *
 * @ description
 * @ author wuyunpeng
 * @ create 2022-07-20 16:20
 */

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        final boolean through = check(urls, requestURI);
//        如果不需要处理,直接放行
        if (through) {
            filterChain.doFilter(request, response);
            return;
        }

        /**
         * pc端
         */
//        如果已登录，直接放行
        Long empID = (Long) request.getSession().getAttribute("employee");
        if (empID != null) {
            BaseContext.setCurrentID(empID);
            filterChain.doFilter(request, response);
            return;
        }

        /**
         * 移动端
         */
        Long userID = (Long) request.getSession().getAttribute("user");
        if (userID != null) {
            BaseContext.setCurrentID(userID);
            filterChain.doFilter(request, response);
            return;
        }
//        如果未登录，则返回登录失败结果,通过输出流的方式向客户端页面返回响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            if (PATH_MATCHER.match(url, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
